﻿// =============================================================================
// TNTTools ReflectionPropertyCache.cs
// Copyright (c) 2013 TNTTechnologies Inc.
// =============================================================================

#region

using System;
using System.Collections.Generic;

using TNTTools.Reflection;
using TNTTools.Reflection.Interfaces;
using TNTTools.Serialization.Interfaces;

#endregion

namespace TNTTools.Serialization{
    public class ReflectionPropertyCache : IReflectionPropertyCache{
        private static Dictionary<Type, ObjectInfo> objectInfoList = new Dictionary<Type, ObjectInfo>();
        private bool isUsingSerializer = false;

        #region IReflectionPropertyCache Members

        /// <summary>
        ///     Loads up from memory or initializes an ObjectInfo
        /// </summary>
        /// <param name="source"></param>
        /// <param name="objectInfo"></param>
        /// <param name="sourceType"></param>
        /// <returns></returns>
        public ObjectInfo GetCachedObjectInfo(
            object source, Type sourceType, ISimpleSerializer serializer, IBasicTypes basicTypes){
            this.isUsingSerializer = true;
            ObjectInfo objectInfo = null;

            if (objectInfoList.ContainsKey(source.GetType())){
                objectInfo = objectInfoList[sourceType];
            } else{
                objectInfo = new ObjectInfo(sourceType, source, serializer, basicTypes);
                objectInfoList.Add(sourceType, objectInfo);
            }
            return objectInfo;
        }

        #endregion

        public ObjectInfo GetCachedObjectInfo(object source, Type sourceType){
            if (this.isUsingSerializer){
                throw new InvalidOperationException(
                    "You can not Initialize the Cache with dependancies to serialization and without dependancies or reflection info will not initialized correctly for serialization.");
            }

            ObjectInfo objectInfo = null;

            if (objectInfoList.ContainsKey(source.GetType())){
                objectInfo = objectInfoList[sourceType];
            } else{
                objectInfo = new ObjectInfo(source, sourceType);
                objectInfoList.Add(sourceType, objectInfo);
            }
            return objectInfo;
        }
    }
}